#!/usr/bin/python
# -*- coding: UTF-8 -*-

from lib.base import Douyin
import random, logging, sys, os

class Fenshen(Douyin):
    def __init__(self, sn):
        super(Fenshen, self).__init__(sn)
        fd = open("{0}/../log/fenshen/{1}.log".format(os.path.dirname(__file__), sn), "w")
        sys.stdout = sys.stderr = fd

    def register_watcheres(self):
        self.device.watchers.reset()
        self.device.watchers.remove()
        self.device.watchers.watched = True
        self.device.watcher("wifi").when(text="取消").when(text="继续观看").click(text="继续观看")
        self.device.watcher("new_version").when(text="以后再说").click()
        self.device.watcher("friends").when(text="发现通讯录好友").when(text="取消").click(text="取消")
        self.device.watchers.run()

    def open_fenshen(self):
        logging.warning("开始打开分身")
        self.app_start("com.bly.dkplat")
        while not self.current_app()['package'] == "com.bly.dkplat":
            logging.warning("不在分身")
            self.sleep()

        logging.warning("进入分身")

        try_num = 0
        #创建分身+号
        while not self.device(resourceId="com.bly.dkplat:id/iv_btn_create").exists():
            if try_num > 30:
                raise RuntimeError("30S没找到创建按钮")

            logging.warning("没找到创建按钮")
            try_num += 1
            self.sleep(1)

        self.click_resource_and_check("com.bly.dkplat:id/iv_btn_create", "点击+")

    def find_douyin(self):
        while not self.device(text="抖音短视频").exists(timeout=3):
            self.swipe_up()

        self.sleep(2)
        bounds = self.device(text="抖音短视频").info['bounds']
        x = random.uniform(int(bounds['left'])+600, int(bounds['left'])+610)
        y = random.uniform(int(bounds['top']+20), int(bounds['bottom']-10))
        #logging.warning("x, y", x, y)
        logging.warning("打开抖音分身")
        self.click(x, y)
        self.sleep(1)
        if self.current_app()['activity'] != "com.bly.dkplat.widget.create.CreateCustomActivity":
            logging.warning("未进入抖音分身设置页面,重新寻找抖音")
            return self.find_douyin()

    def setting(self, name):
        logging.warning("设置appn name")
        resp = self.device(resourceId="com.bly.dkplat:id/et_input").click_exists(timeout=10)
        if not resp:
            self.sleep(1)
            if self.current_app()['activity'] != "com.bly.dkplat.widget.create.SelectCreateAppActivity":
                self.reportClick(resp, "et_input not found")

        for i in range(8):
            self.press_delete()
        self.write_text(str(name))

        self.click_text_and_check("去LOGO水印")

        self.click_resource_and_check("com.bly.dkplat:id/tv_core_version", "os版本")

        self.click_text_and_check("7.8稳定版")

        self.click_text_and_check("高级选项")

        self.click_resource_and_check("com.bly.dkplat:id/cb_virtual_sdcard", "sd卡找不到")

    def set_phone_and_pos(self):
        self.click_resource_and_check("com.bly.dkplat:id/tv_btn_set_device", "点击设置机型")
        
        self.click_text_and_check("华为")
        
        phones = ["小米", "OPPO", "VIVO", "魅族"]
        
        self.click_text_and_check(random.sample(phones, 1)[0])

        self.click_text_and_check("换一换")

        self.click_text_and_check("启用机型伪装")

        self.click_resource_and_check("com.bly.dkplat:id/tv_btn_set_location", "开启虚拟定位")

        if self.device(text="请打开GPS").exists(timeout=3):
            self.click(500, 300)

        logging.warning("开始随机输入一个城市")
        cities = ["遵义", "淄博市", "淄博", "株洲", "珠海市", "珠海", "中山市", "中山", "镇江市", "镇江", "肇庆", "长春市", "漳州市", "漳州", "湛江", "枣庄", "岳阳", "玉林", "榆林", "营口", "银川市", "银川", "宜昌", "宜宾", "扬州市", "扬州", "盐城市", "盐城", "延安", "烟台市", "许昌", "徐州", "邢台", "新余", "新乡", "襄樊", "湘潭", "西宁", "芜湖市", "芜湖", "温州市", "温州", "潍坊", "威海", "天水", "唐山市", "泰州市", "泰州", "泰安", "太原", "台州市", "台州", "石家庄市", "石家庄", "石河子", "绍兴市", "绍兴", "汕头市", "汕头", "日照", "泉州市", "衢州", "清远", "秦皇岛", "齐齐哈尔", "濮阳", "平顶山", "南阳", "南通市", "南通", "南宁市", "南宁", "南昌市", "南昌", "牡丹江", "绵阳市", "绵阳", "梅州", "茂名", "马鞍山", "洛阳", "柳州", "临沂市", "临沂", "聊城", "辽阳", "连云港", "丽水", "廊坊市", "廊坊", "拉萨", "昆明市", "克拉玛依", "开封", "喀什", "九江", "景德镇", "荆州", "锦州", "金华市", "金华", "揭阳", "焦作", "江门市", "江门", "嘉兴", "济宁市", "济宁", "济南市", "吉林", "惠州市", "惠州", "淮南", "淮安", "湖州市", "湖州", "呼和浩特市", "呼和浩特", "衡阳", "合肥市", "合肥", "邯郸市", "邯郸", "海口市", "海口", "哈尔滨市", "桂林", "贵阳市", "贵阳", "赣州", "抚顺", "福州市", "佛山市", "佛山", "鄂尔多斯", "东营", "东莞", "德州", "德阳", "丹东", "大同", "大庆", "大理", "承德", "郴州", "常州市", "常州", "常德", "沧州", "滨州", "本溪", "北海", "保定市", "保定", "宝鸡", "蚌埠", "鞍山", "安阳", "安庆"]
        city = random.sample(cities, 1)[0]
        self.device(text="搜索地点", resourceId="com.bly.dkplat:id/tv_search").click_exists(timeout=10)
        self.write_text(city)
        self.device(resourceId="com.bly.dkplat:id/tv_search").click_exists(timeout=10)
        self.sleep(5)

        if self.device(text="请在以下城市中选择").exists:
            logging.warning("选择城市")
            num = self.device(className="android.widget.LinearLayout").count
            instan = int(random.uniform(5, num-1))
            logging.warning("选择城市:{}:{}".format(num, instan))
            self.device(className="android.widget.LinearLayout", instance=instan).click_exists(timeout=5)
            self.sleep(3)

        num = self.device(className="android.widget.LinearLayout").count
        instan = int(random.uniform(5, num-1))
        logging.warning("选择地址:{}:{}".format(num, instan))
        self.device(className="android.widget.LinearLayout", instance=instan).click_exists(timeout=5)
        self.sleep(3)
        
        self.click_text_and_check("定位到此")

    def make_install(self):
        self.click_resource_and_check("com.bly.dkplat:id/tv_create", "开始制作")

        self.sleep(30)
        self.click(1010, 1820)
        self.click(1010, 1820)

    def click_suipai(self):
        self.click_text_and_check("随拍")

        self.click_text_and_check("去拍摄", 10)

        self.sleep(1)
        self.check_voice_permission()

        #self.click_resource_and_check("com.ss.android.ugc.aweme:id/asl", "关闭随拍")


    def run(self, name):
        logging.warning("按压home")
        self.press_home()

        logging.warning("杀死所有程序")
        self.app_stop_all()

        logging.warning("切换ip")
        self.resetIp()

        self.open_fenshen()
        self.find_douyin()
        self.setting(name)
        self.set_phone_and_pos()

        self.make_install()

        resp = self.device(text="打开").click_exists(timeout=60)

        # 60s未找到打开，可能弹解析包失败
        if not resp:
            if self.device(text="解析软件包时出现问题。").exists():
                self.run(name)
            else:
                self.reportClick(resp, "安装失败")

        self.first_open()
        self.click_suipai()

    def start_once(self, pname):
        self.run(pname)

    def start(self):
        logging.warning("开始执行分身")
        for i in range(20):
            self.run("{}".format(i+1))